package com.sunday.shoufen.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.SlideView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.CityListAdapter;
import com.sunday.shoufen.entity.City;
import com.sunday.shoufen.http.ApiClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/11/6.
 */

public class SelectCityListActivity extends BaseActivity implements SlideView.OnTouchListener {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.index)
    SlideView slideView;
    @Bind(R.id.title_view)
    TextView title;
    private List<City> cityList = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;
    private CityListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_city);
        ButterKnife.bind(this);
        title.setText("选择城市");
        recyclerView.setPadding(0, 0, 0, 0);
        linearLayoutManager = new LinearLayoutManager(mContext);
        adapter = new CityListAdapter(mContext, cityList);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider).build());
        recyclerView.setAdapter(adapter);
        slideView.setOnTouchListener(this);
        getAllCity();
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.text_view:
                        City city = (City) v.getTag();
                        Intent data = new Intent();
                        data.putExtra("cityId", city.getId());
                        data.putExtra("cityName", city.getName());
                        setResult(RESULT_OK, data);
                        //BaseApplication.getInstance().setCityName(city.getValue());
                        //BaseApplication.getInstance().setCityId(Integer.valueOf(city.getId()));
                        // EventBus.getDefault().post(city);
                        finish();
                        break;

                }
            }
        });


    }

    private void getAllCity() {
        showLoadingDialog(0);
        Call<ResultDO<List<City>>> call = ApiClient.getApiAdapter().getAllCity();
        call.enqueue(new Callback<ResultDO<List<City>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<City>>> call, Response<ResultDO<List<City>>> response) {
                dissMissDialog();
                ResultDO<List<City>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0 && resultDO.getResult() != null) {
                    cityList.clear();
                    cityList.addAll(resultDO.getResult());
                    try {
                        for (City item : cityList) {
                            item.setIndex(String.valueOf(item.getPinYin().length() > 0 ? item.getPinYin().charAt(0) : "#"));
                            //item.setIndex(String.valueOf(CharacterParser.getInstance().getSelling(item.getPinYin()).toUpperCase().charAt(0)));
                        }
                    } catch (Exception e) {
                        return;
                    }
                    Collections.sort(cityList, new Compara());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<City>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });


    }

    @Override
    public void onTouch(String letter) {
        for (int i = 0; i < cityList.size(); i++) {
            if (letter.equals(cityList.get(i).getIndex())) {
                smoothMoveToPosition(i);
                break;
            }
        }

    }


    private void smoothMoveToPosition(int index) {
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        if (index <= firstItem) {
            recyclerView.smoothScrollToPosition(index);
        } else if (index <= lastItem) {
            int top = recyclerView.getChildAt(index - firstItem).getTop();
            recyclerView.smoothScrollBy(0, top);
        } else {
            recyclerView.smoothScrollToPosition(index);
        }

    }

    private class Compara implements Comparator<City> {

        @Override
        public int compare(City lhs, City rhs) {
            return lhs.getIndex().compareTo(rhs.getIndex());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        slideView.onDestroy();
    }

}

